import { Card, Table, Row, Col, Statistic, Tag, Modal, Input, Select, Button, Typography } from '@/utils/antd-imports';
import React from 'react';










import DatePicker from 'antd/es/date-picker';


const { Text } = Typography;
const { Option } = Select;
const { RangePicker } = DatePicker;

export const SettlementTab = ({ subProjectsData = [] }) => {
  // 计算结算页签的统计数据
  const calculateSettlementStats = () => {
    const completedProjects = subProjectsData.filter(p => p.status === '已回款');
    const total = completedProjects.length;
    const totalBudget = completedProjects.reduce((sum, p) => sum + (p.budgetAmount || 0), 0);
    const totalActualCost = completedProjects.reduce((sum, p) => sum + (p.actualCost || 0), 0);
    const totalPaidAmount = completedProjects.reduce((sum, p) => sum + (p.paidAmount || 0), 0);
    const profit = totalPaidAmount - totalActualCost;
    const profitRate = totalPaidAmount > 0 ? (profit / totalPaidAmount) * 100 : 0;
    
    // 按项目类型统计
    const packageProjects = completedProjects.filter(p => p.type === '整包');
    const laborProjects = completedProjects.filter(p => p.type === '人力');
    
    return {
      total,
      totalBudget,
      totalActualCost,
      totalPaidAmount,
      profit,
      profitRate,
      packageCount: packageProjects.length,
      laborCount: laborProjects.length,
      packageProfit: packageProjects.reduce((sum, p) => sum + (p.paidAmount || 0) - (p.actualCost || 0), 0),
      laborProfit: laborProjects.reduce((sum, p) => sum + (p.paidAmount || 0) - (p.actualCost || 0), 0),
    };
  };

  const settlementStats = calculateSettlementStats();

  // 显示合同内容的对话框
  const [contractVisible, setContractVisible] = React.useState(false);
  const [currentContract, setCurrentContract] = React.useState('');

  // 筛选状态
  const [filters, setFilters] = React.useState({
    name: '',
    type: undefined,
    clientName: '',
    department: '',
    dateRange: null,
    profitRange: undefined
  });

  const showContract = (contractContent) => {
    setCurrentContract(contractContent);
    setContractVisible(true);
  };

  // 处理筛选变化
  const handleFilterChange = (key, value) => {
    setFilters({
      ...filters,
      [key]: value
    });
  };

  // 重置筛选
  const resetFilters = () => {
    setFilters({
      name: '',
      type: undefined,
      clientName: '',
      department: '',
      dateRange: null,
      profitRange: undefined
    });
  };

  // 应用筛选
  const applyFilters = (data) => {
    return data.filter(item => {
      // 项目名称筛选
      if (filters.name && !item.name.includes(filters.name)) {
        return false;
      }
      
      // 项目类型筛选
      if (filters.type && item.type !== filters.type) {
        return false;
      }
      
      // 客户名称筛选
      if (filters.clientName && !item.clientName.includes(filters.clientName)) {
        return false;
      }
      
      // 部门筛选
      if (filters.department && !item.department.includes(filters.department)) {
        return false;
      }
      
      // 日期范围筛选
      if (filters.dateRange && filters.dateRange.length === 2) {
        const startDate = new Date(filters.dateRange[0]);
        const endDate = new Date(filters.dateRange[1]);
        const actualEndDate = new Date(item.actualEndDate);
        
        if (actualEndDate < startDate || actualEndDate > endDate) {
          return false;
        }
      }
      
      // 利润范围筛选
      if (filters.profitRange) {
        const profit = (item.paidAmount || 0) - (item.actualCost || 0);
        if (filters.profitRange === 'profit' && profit <= 0) {
          return false;
        }
        if (filters.profitRange === 'loss' && profit >= 0) {
          return false;
        }
      }
      
      return true;
    });
  };

  // 子项目表格列定义
  const columns = [
    {
      title: '项目ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
      render: (id) => <Text strong>{id}</Text>
    },
    {
      title: '子项目名称',
      dataIndex: 'name',
      key: 'name',
      width: 180,
      render: (text) => <Text strong>{text}</Text>
    },
    {
      title: '项目类型',
      dataIndex: 'type',
      key: 'type',
      width: 100,
      render: (type) => (
        <Tag color={type === '整包' ? 'geekblue' : 'purple'}>
          {type}
        </Tag>
      )
    },
    {
      title: '客户名称',
      dataIndex: 'clientName',
      key: 'clientName',
      width: 150
    },
    {
      title: '对接人',
      dataIndex: 'contactPerson',
      key: 'contactPerson',
      width: 100
    },
    {
      title: '部门',
      dataIndex: 'department',
      key: 'department',
      width: 100
    },
    {
      title: '科室',
      dataIndex: 'division',
      key: 'division',
      width: 100
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status) => (
        <Tag color={getStatusColor(status)}>
          {status}
        </Tag>
      )
    },
    {
      title: '合同号',
      dataIndex: 'contractNumber',
      key: 'contractNumber',
      width: 120,
      render: (text, record) => (
        <Text 
          underline 
          style={{cursor: 'pointer'}} 
          onClick={() => showContract(record.contractContent || '无合同内容')}
        >
          {text}
        </Text>
      )
    },
    {
      title: '预算金额(元)',
      dataIndex: 'budgetAmount',
      key: 'budgetAmount',
      width: 120,
      render: (amount) => <Text>¥{(amount || 0).toLocaleString()}</Text>
    },
    {
      title: '实际成本(元)',
      dataIndex: 'actualCost',
      key: 'actualCost',
      width: 120,
      render: (amount) => <Text>¥{(amount || 0).toLocaleString()}</Text>
    },
    {
      title: '已回款(元)',
      dataIndex: 'paidAmount',
      key: 'paidAmount',
      width: 120,
      render: (amount) => <Text>¥{(amount || 0).toLocaleString()}</Text>
    },
    {
      title: '利润(元)',
      key: 'profit',
      width: 120,
      render: (_, record) => (
        <Text type={(record.paidAmount - record.actualCost) >= 0 ? 'success' : 'danger'}>
          ¥{((record.paidAmount || 0) - (record.actualCost || 0)).toLocaleString()}
        </Text>
      )
    },
    {
      title: '利润率',
      key: 'profitRate',
      width: 100,
      render: (_, record) => {
        const profitRate = record.paidAmount > 0 
          ? ((record.paidAmount - record.actualCost) / record.paidAmount * 100).toFixed(2)
          : 0;
        return (
          <Text type={profitRate >= 0 ? 'success' : 'danger'}>
            {profitRate}%
          </Text>
        );
      }
    },
    {
      title: '预计结束时间',
      dataIndex: 'expectedEndDate',
      key: 'expectedEndDate',
      width: 120
    },
    {
      title: '实际结束时间',
      dataIndex: 'actualEndDate',
      key: 'actualEndDate',
      width: 120
    }
  ];

  // 获取筛选后的数据
  const filteredData = applyFilters(subProjectsData.filter(p => p.status === '已回款'));

  return (
    <>
      <Row gutter={16} style={{ marginBottom: 24, whiteSpace: 'nowrap', overflowX: 'auto' }}>
        <Col span={6}>
          <Card>
            <Statistic title="已回款项目数" value={settlementStats.total} precision={0} />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic title="总预算(元)" value={settlementStats.totalBudget} precision={0} />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic title="总回款(元)" value={settlementStats.totalPaidAmount} precision={0} />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic 
              title="总利润(元)" 
              value={settlementStats.profit} 
              precision={0} 
              valueStyle={{ color: settlementStats.profit >= 0 ? '#3f8600' : '#cf1322' }} 
            />
          </Card>
        </Col>
      </Row>
      
      <Row gutter={16} style={{ marginBottom: 24, whiteSpace: 'nowrap', overflowX: 'auto' }}>
        <Col span={6}>
          <Card>
            <Statistic title="总成本(元)" value={settlementStats.totalActualCost} precision={0} />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic 
              title="平均利润率" 
              value={settlementStats.profitRate} 
              precision={2} 
              suffix="%" 
              valueStyle={{ color: settlementStats.profitRate >= 0 ? '#3f8600' : '#cf1322' }} 
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic 
              title="整包项目数" 
              value={settlementStats.packageCount} 
              precision={0}
              valueStyle={{ color: '#1890ff' }}
            />
          </Card>
        </Col>
        <Col span={6}>
          <Card>
            <Statistic 
              title="人力项目数" 
              value={settlementStats.laborCount} 
              precision={0}
              valueStyle={{ color: '#722ed1' }}
            />
          </Card>
        </Col>
      </Row>
      
      {/* 筛选区域 */}
      <Card style={{ marginBottom: 16 }}>
        <Row gutter={16} align="middle">
          <Col span={4}>
            <Input 
              placeholder="项目名称" 
              value={filters.name}
              onChange={e => handleFilterChange('name', e.target.value)}
            />
          </Col>
          <Col span={4}>
            <Select
              placeholder="项目类型"
              style={{ width: '100%' }}
              value={filters.type}
              onChange={value => handleFilterChange('type', value)}
              allowClear
            >
              <Option value="整包">整包</Option>
              <Option value="人力">人力</Option>
            </Select>
          </Col>
          <Col span={4}>
            <Input 
              placeholder="客户名称" 
              value={filters.clientName}
              onChange={e => handleFilterChange('clientName', e.target.value)}
            />
          </Col>
          <Col span={4}>
            <Input 
              placeholder="部门" 
              value={filters.department}
              onChange={e => handleFilterChange('department', e.target.value)}
            />
          </Col>
          <Col span={4}>
            <RangePicker 
              style={{ width: '100%' }}
              placeholder={['开始日期', '结束日期']}
              value={filters.dateRange}
              onChange={value => handleFilterChange('dateRange', value)}
            />
          </Col>
          <Col span={4}>
            <Select
              placeholder="利润情况"
              style={{ width: '100%' }}
              value={filters.profitRange}
              onChange={value => handleFilterChange('profitRange', value)}
              allowClear
            >
              <Option value="profit">盈利</Option>
              <Option value="loss">亏损</Option>
            </Select>
          </Col>
        </Row>
        <Row style={{ marginTop: 16 }}>
          <Col>
            <Button type="primary" onClick={() => setFilters({...filters})} style={{ marginRight: 8 }}>
              筛选
            </Button>
            <Button onClick={resetFilters}>
              重置
            </Button>
          </Col>
        </Row>
      </Card>
      
      <Table
        columns={columns}
        dataSource={filteredData}
        rowKey="id"
        pagination={{ pageSize: 10 }}
        scroll={{ x: 2000 }}
        bordered
        size="middle"
      />
      
      <Modal
        title="合同内容"
        visible={contractVisible}
        onCancel={() => setContractVisible(false)}
        footer={null}
        width={800}
      >
        <div style={{ whiteSpace: 'pre-wrap', padding: '20px', backgroundColor: '#f5f5f5', borderRadius: '4px' }}>
          {currentContract}
        </div>
      </Modal>
    </>
  );
};

// 辅助函数
const getStatusColor = (status) => {
  const colors = {
    '未验收': 'default',
    '验收中': 'blue',
    '开票中': 'orange',
    '待回款': 'purple',
    '已回款': 'green'
  };
  return colors[status] || 'default';
};